﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Web;
using System.IO;

namespace Devfw.OpenAuth.Platform
{
    public class Renren
    {
        private string loginUrl = "http://passport.renren.com/PLogin.do";
        private string homeUrl = "http://www.renren.com/Home.do";
        private string uploadPhotoUrl = "http://upload.renren.com/addphotosingle.do";
        private string createalbumUrl = "http://photo.renren.com/ajaxcreatealbum.do";
        private string updateUrl = "http://status.renren.com/doing/update.do";
        private string statusUrl = "http://status.renren.com/publisher/photofeed.do";

        private Encoding encoding = Encoding.UTF8;
       
        
        public Renren( string userID, string password )
        {
            this.UserID = userID;
            this.Password = password;
        }

        public string UserID
        {
            get;set;
        }

        public string Password
        {
            get;set;
        }

        protected ResponseContent LoginResult
        {
            get;
            set;
        }

        protected string RequestToken
        {
            get;
            set;
        }

        public bool Verify()
        {
            string account = this.UserID;
            string password = this.Password; 

            string loginContent = string.Format( "email={0}&password={1}&origURL={2}&domain={3}",
                    HttpUtility.UrlEncode( account ),
                    HttpUtility.UrlEncode( password ),
                    HttpUtility.UrlEncode( homeUrl ),
                    HttpUtility.UrlEncode( "renren.com" )
                );

            LoginResult = Common.GetUrl( loginUrl, encoding, null, "POST", loginContent);
            Match reToken = Regex.Match(LoginResult.content, @"get_check[^\d]{1,100}(\d+)", RegexOptions.IgnoreCase);
            RequestToken = reToken.Groups[0].Value.Replace("get_check:'", "");

            return !LoginResult.content.Contains( "登录帐号或密码错误，请重试" );
        }
        /// <summary>
        /// 创建相册
        /// </summary>
        /// <param name="title">相册名称</param>
        /// <param name="type">相册类型</param>
        /// <returns></returns>
        public ResponseContent Createalbum(string title,RenrenAlbumType type)
        {
            if (LoginResult == null)
                return null;

            string con = string.Format("title={0}&control={1}&password=&passwordProtected=false",
                HttpUtility.UrlEncode(title),
                (int)type

            );
            return Common.GetUrl(createalbumUrl, encoding, LoginResult.cookies, "POST", con);
        }


        /// <summary>
        /// 发布文本状态记录	
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public ResponseContent status_update( string status )
        {
            
            if (string.IsNullOrEmpty(RequestToken))
                return null;

            string updateContent = string.Format("c={0}&raw={1}&isAtHome=1&publisher_form_ticket={2}&requestToken={3}",
                    HttpUtility.UrlEncode( status ),
                    HttpUtility.UrlEncode( status ),
                    RequestToken,
                    RequestToken
                );
            ResponseContent updateResult = Common.GetUrl(updateUrl, encoding, LoginResult.cookies, "POST", updateContent);
            return updateResult;
        }

        public ResponseContent upload( string status, string url )
        {
            WebClient client = new WebClient();
            byte[] b = client.DownloadData( url );
            string[] f = url.Split( '\\', '/' );
            return upload( status, f[f.Length - 1], b );
        }


        public ResponseContent upload( string status, string fileName, byte[] fileData )
        {
            // 上传图片
            
            byte[] uploadData = Common.GetPhotoContent( RequestToken, fileName, fileData );
            ResponseContent uploadResult = Common.GetUrl(uploadPhotoUrl, encoding, LoginResult.cookies, "POST", uploadData, true);
            //string uploadPhotoResult = @"var res={""files"":[{""fileSize"":""171021"",""fileName"":""img_src_284457.jpg"",""code"":1,""msg"":""""}],""photoId"":3.958955755e9,""code"":1,""msg"":"""",""url"":""http:\/\/fmn.rrfmn.com\/fmn052\/20110206\/2025\/p_head_ceRr_49a80008b8e15c3f.jpg""};";
            Match rePhotoId = Regex.Match( uploadResult.content, @"photoId[^\d]{1,100}([\d\.e]+)", RegexOptions.IgnoreCase );
            double photoId = double.Parse( rePhotoId.Groups[1].Value );

            // 发布图片
            string publishPhotoUrl = string.Format( "http://status.renren.com/publisher/photofeed.do?id={0}&status={1}&albumSelect=-1",
                Convert.ToInt64( photoId ),
                HttpUtility.UrlEncode( status )
                );
            string publishPhotoContent = string.Format( "requestToken={0}",
                    RequestToken
                );
            return Common.GetUrl(publishPhotoUrl, encoding, LoginResult.cookies, "POST", publishPhotoContent);
        }

        public ResponseContent status_uploadwithimg(string status, string path, out string phoneid)
        {
            return status_uploadwithimg(status, path,"-1", out phoneid);
        }


        public ResponseContent status_uploadwithimg(string status,string filename, byte[] uploadData, out string phoneid)
        {
            return status_uploadwithimg(status,filename, uploadData, "-1", out phoneid);
        }

        /// <summary>
        /// 上传带图片记录
        /// </summary>
        /// <param name="status">记录信息</param>
        /// <param name="path">图片路径</param>
        /// <param name="albumid">相册id</param>
        /// <param name="phoneid">图片id</param>
        /// <returns></returns>
        public ResponseContent status_uploadwithimg(string status,string path,string albumid,out string phoneid)
        {
            phoneid = string.Empty;
            if (LoginResult == null)
                return null;
            if (string.IsNullOrEmpty(RequestToken))   
                return null;

            string header = string.Format(@"------WebKitFormBoundaryEZzMlOByVUgLgH24
Content-Disposition: form-data; name=""status""


------WebKitFormBoundaryEZzMlOByVUgLgH24
Content-Disposition: form-data; name=""file""; filename=""{0}""
Content-Type: image/jpeg

", Path.GetFileName(path));

            string footer = string.Format(@"
------WebKitFormBoundaryEZzMlOByVUgLgH24
Content-Disposition: form-data; name=""requestToken""

{0}
------WebKitFormBoundaryEZzMlOByVUgLgH24--
", RequestToken);

            byte[] uploadData = Common.GetPhotoContent(path, header, footer);
            ResponseContent uploadResult = Common.GetUrl(uploadPhotoUrl, encoding, LoginResult.cookies, "POST", uploadData, true);
            //string uploadPhotoResult = @"var res={""files"":[{""fileSize"":""171021"",""fileName"":""img_src_284457.jpg"",""code"":1,""msg"":""""}],""photoId"":3.958955755e9,""code"":1,""msg"":"""",""url"":""http:\/\/fmn.rrfmn.com\/fmn052\/20110206\/2025\/p_head_ceRr_49a80008b8e15c3f.jpg""};";
            Match rePhotoId = Regex.Match(uploadResult.content, @"photoId[^\d]{1,100}([\d\.e]+)", RegexOptions.IgnoreCase);
            phoneid  = rePhotoId.Groups[1].Value;
            
            //发布信息
            string publishPhotoUrl = string.Format("http://status.renren.com/publisher/photofeed.do?id={0}&status={1}&albumSelect={2}",
                Convert.ToInt64(phoneid),
                HttpUtility.UrlEncode(status),
                HttpUtility.UrlEncode(albumid)
                );
            string publishPhotoContent = string.Format("requestToken=-{0}",
                    RequestToken
                );
            return Common.GetUrl(publishPhotoUrl, encoding, LoginResult.cookies, "POST", publishPhotoContent);
        }

        public ResponseContent status_uploadwithimg(string status, string filename,byte[] uploadData, string albumid, out string phoneid)
        {
            phoneid = string.Empty;
            if (LoginResult == null)
                return null;
            if (string.IsNullOrEmpty(RequestToken))
                return null;

            string header = string.Format(@"------WebKitFormBoundaryEZzMlOByVUgLgH24
Content-Disposition: form-data; name=""status""


------WebKitFormBoundaryEZzMlOByVUgLgH24
Content-Disposition: form-data; name=""file""; filename=""{0}""
Content-Type: image/jpeg

", filename);

            string footer = string.Format(@"
------WebKitFormBoundaryEZzMlOByVUgLgH24
Content-Disposition: form-data; name=""requestToken""

{0}
------WebKitFormBoundaryEZzMlOByVUgLgH24--
", RequestToken);

            uploadData = Common.GetPhoto(header, footer,uploadData);
            ResponseContent uploadResult = Common.GetUrl(uploadPhotoUrl, encoding, LoginResult.cookies, "POST", uploadData, true);
            //string uploadPhotoResult = @"var res={""files"":[{""fileSize"":""171021"",""fileName"":""img_src_284457.jpg"",""code"":1,""msg"":""""}],""photoId"":3.958955755e9,""code"":1,""msg"":"""",""url"":""http:\/\/fmn.rrfmn.com\/fmn052\/20110206\/2025\/p_head_ceRr_49a80008b8e15c3f.jpg""};";
            Match rePhotoId = Regex.Match(uploadResult.content, @"photoId[^\d]{1,100}([\d\.e]+)", RegexOptions.IgnoreCase);
            phoneid = rePhotoId.Groups[1].Value;

            //发布信息
            string publishPhotoUrl = string.Format("http://status.renren.com/publisher/photofeed.do?id={0}&status={1}&albumSelect={2}",
                Convert.ToInt64(phoneid),
                HttpUtility.UrlEncode(status),
                HttpUtility.UrlEncode(albumid)
                );
            string publishPhotoContent = string.Format("requestToken=-{0}",
                    RequestToken
                );
            return Common.GetUrl(publishPhotoUrl, encoding, LoginResult.cookies, "POST", publishPhotoContent);
        }
    }
}
